using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Department;
using B.S.NewMedical.Api.Write.Common;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Department
{
    /// <summary>
    /// 删除科室命令处理器
    /// </summary>
    public class DeleteDepartmentCommandHandler : IRequestHandler<DeleteDepartmentCommand, BatchDeleteResult>
    {
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;

        public DeleteDepartmentCommandHandler(IBaseRepository<DepartmentModel> departmentRepository)
        {
            _departmentRepository = departmentRepository ?? throw new ArgumentNullException(nameof(departmentRepository));
        }

        /// <summary>
        /// 处理批量删除科室命令
        /// </summary>
        /// <param name="request">批量删除科室命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>批量删除结果</returns>
        public async Task<BatchDeleteResult> Handle(DeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            var result = new BatchDeleteResult();
            var successIds = new List<int>();
            var failedIds = new List<int>();
            var subDepartmentIds = new List<int>(); // 有下级科室的ID
            var notFoundIds = new List<int>(); // 不存在或已删除的ID

            foreach (var id in request.Ids)
            {
                try
                {
                    // 查找要删除的科室
                    var department = await _departmentRepository.GetValue(id);
                    if (department != null && !department.IsDeleted)
                    {
                        // 检查是否有下级科室
                        var hasSubDepartments = _departmentRepository.GetAll()
                            .Any(d => d.ParetId == id && !d.IsDeleted);

                        if (hasSubDepartments)
                        {
                            // 如果有下级科室，不能删除
                            failedIds.Add(id);
                            subDepartmentIds.Add(id);
                            result.FailCount++;
                            continue;
                        }

                        // 软删除：设置删除状态和更新时间
                        department.IsDeleted = true;
                        department.UpdateTime = DateTime.Now;
                        department.UpdatePeople = request.UpdatePeople;

                        await _departmentRepository.UpdateAsync(department);
                        successIds.Add(id);
                        result.SuccessCount++;
                    }
                    else
                    {
                        failedIds.Add(id);
                        notFoundIds.Add(id);
                        result.FailCount++;
                    }
                }
                catch (Exception)
                {
                    failedIds.Add(id);
                    notFoundIds.Add(id);
                    result.FailCount++;
                }
            }

            result.FailedIds = failedIds;
            result.Success = result.FailCount == 0;

            // 生成详细的错误信息
            if (result.Success)
            {
                result.Message = $"成功删除 {result.SuccessCount} 个科室";
            }
            else
            {
                var errorMessages = new List<string>();
                
                if (subDepartmentIds.Count > 0)
                {
                    errorMessages.Add($"科室ID {string.Join(", ", subDepartmentIds)} 有下级科室，不能删");
                }
                
                if (notFoundIds.Count > 0)
                {
                    errorMessages.Add($"科室ID {string.Join(", ", notFoundIds)} 不存在或已被删除");
                }

                if (result.SuccessCount > 0)
                {
                    result.Message = $"成功删除 {result.SuccessCount} 个科室，失败 {result.FailCount} 个科室。{string.Join("；", errorMessages)}";
                }
                else
                {
                    result.Message = $"删除失败：{string.Join("；", errorMessages)}";
                }
            }

            return result;
        }
    }
}